package NowInfo

import (
	"net/http"
	"Shares/Model"
	"io/ioutil"
	"encoding/json"
	"log"
	"fmt"
	"strconv"
	"github.com/jinzhu/gorm"
)

const appid="ff8a6e4f19d76893969da2184f198dc2"

type nowInfoSrc struct {
	ErrorCode int `json:"error_code"`
	Data []indexInfo`json:"data"`
	//Data []struct{
	//	Date string`json:"date"`
	//	Open string`json:"open"`
	//	Close string`json:"close"`
	//	High string`json:"high"`
	//	Low string`json:"low"`
	//	Volume string`json:"volume"`
	//	Code string`json:"code"`
	//}
	Reason string `json:"reason"`
}


type indexInfo struct {
	Code string`json:"code"`
	Name string`json:"name"`
	ChangePercent string`json:"changepercent"`
	Trade string`json:"trade"`
	Open string`json:"open"`
	High string`json:"high"`
	Low string`json:"low"`
	Settlement string`json:"settlement"`
	Volume string`json:"volume"`
	TurnOverRatio string`json:"turnoverratio"`
	Amount string`json:"amount"`
	Pb string`json:"pb"`
	Mktcap string`json:"mktcp"`
	Nmc string`json:"nmc"`
}

type Today struct {
	src nowInfoSrc
	des []Model.SharesNowInfo
}

func(self*Today)GetInfo(){
	res,err:=http.Get("http://api.shenjian.io/?appid="+appid)
	if err!=nil{
		log.Fatal(err)
	}
	data,err:=ioutil.ReadAll(res.Body)
	err=json.Unmarshal(data,&self.src)
	if err!=nil{
		log.Fatal(err)
	}
}

func(this*Today)Trans(){
	var res =new(Model.SharesNowInfo)
	for _,self:=range this.src.Data{
		code:=self.Code
		res.Code,_=strconv.Atoi(code)
		res.Name=self.Name
		res.ChangePercent,_=strconv.ParseFloat(self.ChangePercent,64)
		res.Trade,_=strconv.ParseFloat(self.Trade,64)
		res.Open,_=strconv.ParseFloat(self.Open,64)
		res.High,_=strconv.ParseFloat(self.High,64)
		res.Low,_=strconv.ParseFloat(self.Low,64)
		res.Volume,_=strconv.ParseFloat(self.Volume,64)
		res.Settlement,_=strconv.ParseFloat(self.Settlement,64)
		res.TurnOverRatio,_=strconv.ParseFloat(self.TurnOverRatio,64)
		res.Amount,_=strconv.ParseFloat(self.Amount,64)
		res.Pb,_=strconv.ParseFloat(self.Pb,64)
		res.Mktcap,_=strconv.ParseFloat(self.Mktcap,64)
		res.Nmc,_=strconv.ParseFloat(self.Nmc,64)

	//	fmt.Printf("%+v\n",*res)
		this.des=append(this.des,*res)
	}
}

func(self*Today)Save(){
	db, err := gorm.Open("mysql", "root:cxx15755599659@/Ticket?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()
	db.AutoMigrate(&Model.SharesNowInfo{})
	for _,elem:=range self.des{
		db.Create(&elem)
		fmt.Printf("%+v\n",elem)
	}
}

func(self*Today)Start(){
	self.GetInfo()
	self.Trans()
	self.Save()
}